<?php
/**
 * 11abacus Framework
 *
 * PHP version 5
 *
 * LICENSE:
 *
 * Copyright (c) 2008, 11abacus / Philippe Jausions
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *   - Redistributions of source code must retain the above copyright notice,
 *     this list of conditions and the following disclaimer.
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *   - Neither the name of the 11abacus nor the names of its contributors may
 *     be used to endorse or promote products derived from this software
 *     without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * @category  Framework
 * @package   Abacus11_Framework
 * @author    Philippe Jausions <Philippe.Jausions@11abacus.com>
 * @copyright 2008 11abacus / Philippe Jausions
 * @license   http://www.opensource.org/licenses/bsd-license.php New BSD
 * @link      http://pear.11abacus.com/package/Abacus11_Framework
 */

/**
 * Required interface declaration
 */
require_once 'Abacus11/FrameworkInterface.php';

/**
 * 11abacus Framework
 *
 * @category  Framework
 * @package   Abacus11_Framework
 * @author    Philippe Jausions <Philippe.Jausions@11abacus.com>
 * @copyright 2008 11abacus / Philippe Jausions
 * @license   http://www.opensource.org/licenses/bsd-license.php New BSD
 * @link      http://pear.11abacus.com/package/Abacus11_Framework
 * 
 * @property-read Abacus11_Framework_Controller $controller Controller
 */
class Abacus11_Framework implements Abacus11_FrameworkInterface
{
    /**
     * Status is unknown
     */
    const STATUS_UNKNOWN = -1;

    /**
     * Status is "available"
     */
    const STATUS_AVAILABLE = 200;

    /**
     * Status is "disabled"
     */
    const STATUS_DISABLED = 403;

    /**
     * Status is "Login is required"
     */
    const STATUS_LOGIN = 401;

    /**
     * Status is "Payment is required"
     */
    const STATUS_INVOICE = 402;

    /**
     * Status is "Not found"
     */
    const STATUS_NOTFOUND = 404;

    /**
     * Status is "Under maintenance"
     */
    const STATUS_MAINTENANCE = 503;

    /**
     * Status is "An error has occured"
     */
    const STATUS_ERROR = 500;
    
    /**
     * Framework scope
     */
    const SCOPE_FRAMEWORK = 'framework';

    /**
     * Module scope
     */
    const SCOPE_MODULE = 'module';

    /**
     * Action scope
     */
    const SCOPE_ACTION = 'action';
    
    /**
     * View scope
     */
    const SCOPE_VIEW = 'view';
    
    /**
     * Data scope
     */
    const SCOPE_DATA = 'data';

    /**
     * Request scope
     */
    const SCOPE_REQUEST = 'request';

    /**
     * Response scope
     */
    const SCOPE_RESPONSE = 'response';

    /**
     * Controller scope
     */
    const SCOPE_CONTROLLER = 'controller';
    
    /**
     * Singleton instance
     *
     * @var CheapTrips_Framework
     */
    protected static $instance = null;

    /**
     * Controller
     *
     * @var Abacus11_Framework_Controller
     */
    protected $controller;

    /**
     * Returns the singleton instance
     *
     * @param Abacus11_FrameworkInterface $instance frameword instance to register
     * 
     * @return Abacus11_FrameworkInterface
     */
    static public function singleton(Abacus11_FrameworkInterface $instance = null)
    {
        if (self::$instance === null) {
            if ($instance === null) {
                self::$instance = new self();
            } else {
                self::$instance = $instance;
            }
        }

        return self::$instance;
    }

    /**
     * Processes the request
     *
     * @return void
     */
    static public function run()
    {
        $framework = self::singleton();
        $framework->start();
        $framework->getController()->run();
        $framework->stop();
    }

    /**
     * Returns the controller used
     * 
     * @return Abacus11_Framework_Controller the controller instance
     */
    public function getController()
    {
        if ($this->controller === null) {
            $this->controller = Abacus11_Framework_Controller::singleton();
        }
        return $this->controller;
    }

    /**
     * Property getter
     *
     * @param string $name Property name
     * 
     * @return mixed
     */
    public function __get($name)
    {
        throw new Abacus11_Framework_Exception_NotFound('No such property "'
                .$name.'"', self::SCOPE_FRAMEWORK);
    }

    /**
     * Property setter
     *
     * @param string $name  Property name
     * @param mixed  $value Property value
     * 
     * @return void
     */
    public function __set($name, $value)
    {
        throw new Abacus11_Framework_Exception_NotFound('No such writable property "'
                .$name.'"', self::SCOPE_FRAMEWORK);
    }
    
    /**
     * Returns a module instance
     *
     * @param string $name Name of module to return
     * 
     * @return Abacus11_Framework_ModuleInterface Module instance
     */
    public function getModule($name)
    {
        if ($this->getModuleStatus($name) === self::STATUS_DISABLED) {
            throw new Abacus11_Framework_Exception('Module "'.$name
                                   .'" is not available', self::SCOPE_MODULE);
        }

        static $classes = array();

        if (@$classes[$name] === null) {
            $classes[$name] = false;

            list($class, $file) = $this->mapModuleName($name);

            if (class_exists($class)) {
                $classes[$name] = $class;
            } else {
                $fp = @fopen($file, 'r', true);
                if ($fp !== false) {
                    fclose($fp);
                    include_once $file;
                }
                if (!class_exists($class, false)) {
                    throw new Abacus11_Framework_Exception_NotFound('Could not find module "'
                            .$name.'" in "'.$file.'"', self::SCOPE_MODULE);
                }
                $classes[$name] = $class;
            }
        }

        if ($classes[$name] === false) {
            throw new Abacus11_Framework_Exception_NotFound('Could not find module "'
                                                .$name.'"', self::SCOPE_MODULE);
        }

        $class  = $classes[$name];
        $module = new $class();
        if (!($module instanceof Abacus11_Framework_ModuleInterface)) {
            throw new Abacus11_Framework_Exception('Invalid module "'.$name.'"',
                                                   self::SCOPE_MODULE);
        }
        $module->setController($this->getController());
        return $module;
    }
    
    /**
     * Maps the module name to class and file path
     *
     * @param string $name module name
     * 
     * @return array(className, filePath)
     */
    protected function mapModuleName($name)
    {
        return array(
            'Abacus11_Framework_Module_'.$name,
            'Abacus11/Framework/Module/'.$name.'.php',
        );
    }
    
    /**
     * Returns the status of the module
     *
     * @param string|Abacus11_Framework_ModuleInterface $module name or instance
     * 
     * @return Abacus11_Framework::STATUS_* Status constant
     */
    public function getModuleStatus($module)
    {
        if ($module instanceof Abacus11_Framework_ModuleInterface) {
            return $module->getStatus();
        }
        return self::STATUS_UNKNOWN;
    }

    /**
     * Starts the framework 
     *
     * @return void
     */
    public function start() 
    {
    }

    /**
     * Stops the framework 
     *
     * @return void
     */
    public function stop()
    {
    }

    /**
     * Returns a renderer
     *
     * @return Abacus11_Framework_RendererInterface
     */
    public function getRenderer()
    {
        static $renderer;
        if ($renderer === null) {
             $renderer = new Abacus11_Framework_Renderer();
        }
        return $renderer;
    }
}

?>